<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <div>
      <div class="btns">
        <button data-path="news">新闻</button>
        <button data-path="play">娱乐</button>
        <button data-path="game">游戏</button>
      </div>
      <!-- 容器 -->
      <div class="view"></div>
    </div>
    <script>
      /* 
      serve服务器启动项目
      npm i serve -g
      serve -v 查看版本
      serve -s 启动服务器
      */
      const routes = [
        {
          path: "news",
          content: "我是新闻主页",
        },
        {
          path: "play",
          content: "我是娱乐主页",
        },
        {
          path: "game",
          content: "我是游戏主页",
        },
      ];
      const btns = document.querySelectorAll(".btns button");
      const view = document.querySelector(".view");
      //给所有的button绑定点击事件
      for (var i = 0; i < btns.length; i++) {
        btns[i].onclick = function () {
          /*
          使用history的pushState或者replaceState方法,改变路径地址,并且不刷新浏览器
          */
          history.pushState(null, null, this.dataset.path);
          // history.replaceState(null, null, this.dataset.path);

          //直接遍历路由表
          routes.forEach((item) => {
            if (item.path === this.dataset.path) {
              view.textContent = item.content;
            }
          });
        };
      }
      /* 
      onpopstate事件监听历史记录的改动
      */
      window.onpopstate = () => {
        // console.log(123);
        console.log(location.pathname);
        const nowPath = location.pathname.slice(1);
        //直接遍历路由表
        routes.forEach((item) => {
          if (item.path === nowPath) {
            view.textContent = item.content;
          }
        });
      };
    </script>
  </body>
</html>
